package com.thoughtworks.yuyijq.generate.element;

import org.apache.commons.lang.builder.ToStringBuilder;

import java.util.Stack;

/**
 * User: yuyijq
 * Date: Oct 10, 2010
 * Time: 2:28:11 PM
 */
public class MethodBodyElement implements MemberElement{
    public String getMethodBodyStatement() {
        return methodBodyStatement;
    }

    private String methodBodyStatement;
    public int read(String source) {
        int readLength = 0;
        String newSource = source.trim();
        int offset = source.length() - newSource.length();

        StringBuilder stringBuilder = new StringBuilder();
        Stack<Integer> stack = new Stack<Integer>();
        for(int i = 0;i < newSource.length();++i){
            stringBuilder.append(newSource.charAt(i));
             if(newSource.charAt(i) == '{'){
                 stack.push((int)newSource.charAt(i));
             }

            if(newSource.charAt(i) == '}'){
                if(stack.peek() == '{'){
                    stack.pop();
                }
            }

            if(stack.size() == 0){
                methodBodyStatement = stringBuilder.toString();
                readLength = i+offset;
                break;
            }
        }
        methodBodyStatement = methodBodyStatement.trim();
        return readLength;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).
                append("methodBodyStatement", methodBodyStatement).
                toString();
    }
}
